import React, { useState, useEffect, useMemo } from 'react';
import { List, ListItem, ListItemAvatar, Avatar, ListItemText, Typography, Divider, IconButton, Menu, MenuItem, Skeleton, Box } from '@mui/material';
import { MoreVert as MoreVertIcon } from '@mui/icons-material';
import { useMessages } from '../MessagesContext';
import { MessageService } from '../services/MessageService';
import { useAuth } from '../../auth/AuthContext';

interface User {
  id: number;
  name: string;
  avatar?: string;
}

interface MessageListProps {
  onSelectMessage: (messageId: number) => void;
  loading?: boolean;
}

// 使用React.memo优化组件渲染性能
const MessageList: React.FC<MessageListProps> = React.memo(({ onSelectMessage, loading = false }) => {
  const { messages, deleteMessage } = useMessages();
  const { user } = useAuth();
  const [internalLoading, setInternalLoading] = useState(false);
  const [unreadCount, setUnreadCount] = useState<Record<number, number>>({});
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [selectedConversation, setSelectedConversation] = useState<number | null>(null);
  
  // 使用useMemo优化对话分组和排序的性能
  const groupedConversations = useMemo(() => {
    if (!user || !messages.length) return [];
    
    // 按对话分组
    const conversations: Record<number, any> = {};
    
    messages.forEach(message => {
      const otherUserId = message.senderId === user.id ? message.receiverId : message.senderId;
      
      if (!conversations[otherUserId]) {
        conversations[otherUserId] = {
          id: message.id,
          userId: otherUserId,
          userName: message.senderName === user.name ? message.receiverName : message.senderName,
          lastMessage: message.content,
          timestamp: new Date(message.timestamp).getTime(),
          isRead: message.isRead || message.senderId === user.id
        };
      } else if (new Date(message.timestamp).getTime() > conversations[otherUserId].timestamp) {
        // 更新最新消息
        conversations[otherUserId] = {
          ...conversations[otherUserId],
          id: message.id,
          lastMessage: message.content,
          timestamp: new Date(message.timestamp).getTime(),
          isRead: message.isRead || message.senderId === user.id
        };
      }
    });
    
    // 转换为数组并按时间排序
    return Object.values(conversations).sort((a, b) => b.timestamp - a.timestamp);
  }, [messages, user]);
  
  // 加载未读消息数量
  useEffect(() => {
    const loadUnreadCount = async () => {
      if (!user) return;
      
      try {
        setInternalLoading(true);
        const count = await MessageService.getUnreadMessageCount();
        setUnreadCount(count);
      } catch (error) {
        console.error('获取未读消息数量失败:', error);
      } finally {
        setInternalLoading(false);
      }
    };
    
    loadUnreadCount();
  }, [user]);
  
  const handleDeleteConversation = async (userId: number) => {
    if (!user) return;
    
    try {
      await deleteMessage(userId);
      setAnchorEl(null);
    } catch (error) {
      console.error('删除对话失败:', error);
    }
  };
  
  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>, userId: number) => {
    event.stopPropagation();
    setAnchorEl(event.currentTarget);
    setSelectedConversation(userId);
  };
  
  const handleMenuClose = () => {
    setAnchorEl(null);
  };
  
  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    const now = new Date();
    const isToday = date.getDate() === now.getDate() && 
                   date.getMonth() === now.getMonth() && 
                   date.getFullYear() === now.getFullYear();
    
    if (isToday) {
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } else {
      return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
    }
  };
  
  // 渲染加载状态
  if (loading || internalLoading) {
    return (
      <List>
        {[1, 2, 3, 4, 5].map((item) => (
          <React.Fragment key={item}>
            <ListItem alignItems="flex-start">
              <ListItemAvatar>
                <Skeleton variant="circular" width={40} height={40} />
              </ListItemAvatar>
              <ListItemText
                primary={<Skeleton width="70%" />}
                secondary={<Skeleton width="90%" />}
              />
              <Skeleton variant="text" width={40} />
            </ListItem>
            <Divider variant="inset" component="li" />
          </React.Fragment>
        ))}
      </List>
    );
  }
  
  // 渲染空状态
  if (groupedConversations.length === 0) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', p: 3 }}>
        <Typography variant="body1" color="text.secondary">
          暂无私信对话
        </Typography>
      </Box>
    );
  }
  
  return (
    <>
      <List sx={{ width: '100%', bgcolor: 'background.paper', p: 0 }}>
        {groupedConversations.map((conversation: any) => (
          <React.Fragment key={conversation.userId}>
            <ListItem 
              alignItems="flex-start" 
              onClick={() => onSelectMessage(conversation.id)}
              sx={{ 
                cursor: 'pointer',
                '&:hover': { bgcolor: 'action.hover' },
                bgcolor: conversation.isRead ? 'inherit' : 'rgba(25, 118, 210, 0.08)'
              }}
              secondaryAction={
                <IconButton edge="end" onClick={(e) => handleMenuOpen(e, conversation.userId)}>
                  <MoreVertIcon />
                </IconButton>
              }
            >
              <ListItemAvatar>
                <Avatar alt={conversation.userName}>
                  {conversation.userName.charAt(0).toUpperCase()}
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={
                  <Typography
                    component="span"
                    variant="body1"
                    color="text.primary"
                    sx={{ fontWeight: conversation.isRead ? 'normal' : 'bold' }}
                  >
                    {conversation.userName}
                  </Typography>
                }
                secondary={
                  <React.Fragment>
                    <Typography
                      component="span"
                      variant="body2"
                      color="text.primary"
                      sx={{
                        display: 'inline',
                        fontWeight: conversation.isRead ? 'normal' : 'medium',
                        color: conversation.isRead ? 'text.secondary' : 'text.primary',
                      }}
                    >
                      {conversation.lastMessage.length > 20 
                        ? `${conversation.lastMessage.substring(0, 20)}...` 
                        : conversation.lastMessage}
                    </Typography>
                    <Typography
                      component="span"
                      variant="caption"
                      color="text.secondary"
                      sx={{ display: 'block', mt: 0.5 }}
                    >
                      {formatTime(conversation.timestamp)}
                    </Typography>
                  </React.Fragment>
                }
              />
            </ListItem>
            <Divider variant="inset" component="li" />
          </React.Fragment>
        ))}
      </List>
      
      <Menu
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleMenuClose}
      >
        <MenuItem onClick={() => selectedConversation && handleDeleteConversation(selectedConversation)}>
          删除对话
        </MenuItem>
      </Menu>
    </>
  );
});

export default MessageList;